﻿
Imports std

Public Module componentGenerator
    Private components As map(Of String, _do(Of Object)) = Nothing

    Sub New()
        components = New map(Of String, _do(Of Object))()
        registerComponents()
    End Sub

    Private Sub registerComponents()
        register(Of gravitation_rc4_star)()
        register(Of gravitation_rc_pac_star)("gravitation_star")
        register(Of gravitation_rc4_planet)()
        register(Of gravitation_rc_pac_planet)("gravitation_planet")

        register(Of passthroughDistributor)()
        register(Of jobtypesDistributor)()
        register(Of spreadDistributor)()
        register(Of spreadDistributor)("redundanceDistributor")
        register(Of randomDistributor)()
        register(Of hashDistributor)()
        register(Of storageJobRandomDistributor)()

        register(Of storoomDetector)()
        register(Of rc4Detector)()
        register(Of rc_pac_detector)()
        register(Of rc_pac_detector)("rcDetector")
    End Sub

    Public Function register(ByVal name As String, ByVal ctor As _do(Of Object)) As Boolean
        name = strtolower(name)
        If ctor Is Nothing OrElse isemptystring(name) Then
            Return False
        ElseIf components.find(name) <> components.end() Then
            raiseError(errorHandle.errorType.warning, "duplicate name ", name, " found")
            Return False
        Else
            components(name) = ctor
            Return True
        End If
    End Function

    Public Function register(Of T)(ByVal name As String) As Boolean
        Return register(name, AddressOf alloc(Of T))
    End Function

    Public Function register(Of T)() As Boolean
        Return register(Of T)(GetType(T).Name())
    End Function

    Public Function generate(ByVal name As String, ByRef rtn As Object) As Boolean
        Dim it As map(Of String, _do(Of Object)).iterator = Nothing
        it = components.find(strtolower(name))
        If it = components.end() Then
            raiseError(errorHandle.errorType.warning, "cannot find related component ", name)
            Return False
        Else
            rtn = do_((+it).second, Nothing)
            If rtn Is Nothing Then
                raiseError(errorHandle.errorType.warning, "cannot generate component ", name)
                Return False
            Else
                Return True
            End If
        End If
    End Function
End Module
